<template>
  <div class="employee-manage">
    <!-- 员工列表 -->
    <el-card class="employee-list">
      <!-- 头部筛选和按钮 -->
      <template #header>
        <div class="card-header">
          <span>员工列表</span>
          <el-button type="primary" @click="openAddDialog">添加员工</el-button>
          <el-select
            v-model="currentBranchId"
            placeholder="选择支行查询员工"
            style="width: 200px"
            @change="getEmployeesByBranchId($event === 'null' ? null : $event)"
          >
            <el-option label="全体员工" value="null" />
            <el-option
              v-for="branch in branches"
              :key="branch.branch_id"
              :label="branch.branch_name"
              :value="branch.branch_id"
            />
          </el-select>
        </div>
      </template>

      <el-table :data="paginatedEmployees" v-loading="loading" style="width: 100%">
        <el-table-column prop="employee_name" label="员工姓名" width="180" />
        <el-table-column prop="branch_id" label="支行ID" width="180" />
        <el-table-column prop="role" label="职称" width="180" />
        <el-table-column prop="phone" label="电话" width="180" />
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteEmployee(scope.row.employee_id)">删除</el-button>
            <el-button size="small" @click="assignToBranch(scope.row.employee_id)">分配到支行</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      />
    </el-card>

    <!-- 添加员工弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加员工"
      @close="resetAddForm"
    >
      <el-form :model="newEmployee" :rules="rules" ref="addFormRef" label-width="120px">
        <el-form-item label="员工姓名" prop="employee_name">
          <el-input v-model="newEmployee.employee_name" />
        </el-form-item>
        <el-form-item label="支行" prop="branchId">
          <el-select v-model="newEmployee.branchId" placeholder="请选择支行">
            <el-option
              v-for="branch in branches"
              :key="branch.branch_id"
              :label="branch.branch_name"
              :value="branch.branch_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职称" prop="role">
          <el-input v-model="newEmployee.role" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="newEmployee.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addEmployee">保存</el-button>
      </template>
    </el-dialog>

    <!-- 编辑员工弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑员工信息"
      @close="resetEditForm"
    >
      <el-form :model="editEmployee" :rules="rules" ref="editFormRef" label-width="120px">
        <el-form-item label="员工姓名" prop="employee_name">
          <el-input v-model="editEmployee.employee_name" />
        </el-form-item>
        <el-form-item label="支行" prop="branchId">
          <el-select v-model="editEmployee.branchId" placeholder="请选择支行">
            <el-option
              v-for="branch in branches"
              :key="branch.branch_id"
              :label="branch.branch_name"
              :value="branch.branch_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职称" prop="role">
          <el-input v-model="editEmployee.role" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editEmployee.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateEmployee">保存</el-button>
      </template>
    </el-dialog>

    <!-- 分配员工到支行弹窗 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="分配员工到支行"
      @close="resetAssignForm"
    >
      <el-form :model="assignEmployee" :rules="rules" ref="assignFormRef" label-width="120px">
        <el-form-item label="支行" prop="branch_id">
          <el-select v-model="assignEmployee.branch_id" placeholder="请选择支行">
            <el-option
              v-for="branch in branches"
              :key="branch.branch_id"
              :label="branch.branch_name"
              :value="branch.branch_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAssign">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request.js';

// 员工列表
const employees = ref([]);
const currentBranchId = ref('');
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 添加员工表单
const newEmployee = ref({
  employee_name: '',
  branchId: '',
  role: '',
  phone: ''
});
const addFormRef = ref(null);
const addDialogVisible = ref(false);

// 编辑员工表单
const editEmployee = ref({});
const editDialogVisible = ref(false);
const editFormRef = ref(null);

// 分配员工到支行表单
const assignEmployee = ref({
  employee_id: '',
  branch_id: ''
});
const assignDialogVisible = ref(false);
const assignFormRef = ref(null);

// 支行列表
const branches = ref([]);

//计算属性处理前端分页
const paginatedEmployees = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return employees.value.slice(start, end);
});
// 校验规则
const rules = {
  employee_name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
  branchId: [{ required: true, message: '请选择支行', trigger: 'change' }],
  role: [{ required: true, message: '请输入角色', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' },{ min: 15, max: 15, message: '请输入 15 位电话号码', trigger: 'blur' }]
};

// 根据支行ID获取员工列表
const getEmployeesByBranchId = async (branchId) => {
  try {
    loading.value = true;
    const params = {};
    if (branchId) {
      params.branch_id = branchId;
    }
    const response = await request.get('/employees/getByBranchId', { params });
    console.log('响应数据:', response); // 添加日志输出
    if (response.code === 0) {
      employees.value = response.data || [];
      total.value = employees.value.length;
    } else {
      employees.value = [];
      total.value = 0;
      ElMessage.error(response.message || '获取员工失败');
    }
  } catch (error) {
    ElMessage.error('请求失败: ' + error.message);
    employees.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取支行列表
const getBranches = async () => {
  try {
    const response = await request.get('/branches/getAll');
    if (response.code === 0) {
      branches.value = response.data;
    } else {
      branches.value = [];
      ElMessage.error(response.message || '获取支行列表失败');
    }
  } catch (error) {
    ElMessage.error('获取支行列表失败');
  }
};

// 打开添加弹窗
const openAddDialog = () => {
  addDialogVisible.value = true;
};

// 重置添加表单
const resetAddForm = () => {
  addFormRef.value?.resetFields();
  newEmployee.value = {
    employee_name: '',
    branchId: '',
    role: '',
    phone: ''
  };
};

// 添加员工
const addEmployee = async () => {
  try {
    const formData = {
      employee_name: newEmployee.value.employee_name,
      role: newEmployee.value.role,
      phone: newEmployee.value.phone,
      branch_id: newEmployee.value.branchId 
    };
    
    console.log('添加员工表单数据:', formData); // 调试用，查看提交的数据
    
    const response = await request.post('/employees', formData);
    
    if (response.code === 0) {
      ElMessage.success('添加员工成功');
      addDialogVisible.value = false;
      getEmployeesByBranchId(currentBranchId.value);
      resetAddForm();
    } else {
      ElMessage.error(response.message || '添加员工失败');
    }
  } catch (error) {
    ElMessage.error('请求失败: ' + error.message);
  }
};
// 打开编辑弹窗
const openEditDialog = (employee) => {
  editEmployee.value = { ...employee };
  editDialogVisible.value = true;
};

// 重置编辑表单
const resetEditForm = () => {
  editFormRef.value?.resetFields();
  editEmployee.value = {};
};

// 更新员工信息
const updateEmployee = () => {
  editFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      const response = await request.put('/employees', editEmployee.value);
      if (response.code === 0) {
        ElMessage.success('员工信息更新成功');
        editDialogVisible.value = false;
        getEmployeesByBranchId(editEmployee.value.branchId, currentPage.value);
      }
    } catch (error) {
      ElMessage.error('员工信息更新失败');
    }
  });
};

// 删除员工
const deleteEmployee = async (employeeId) => {
  try {
    await ElMessageBox.confirm('确定要删除此员工吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const employee = { employee_id: employeeId };
    console.log('删除请求参数:', employee); // 新增日志
    const response = await request.delete('/employees', { data: employee });
    if (response.code === 0) {
      ElMessage.success('员工删除成功');
      getEmployeesByBranchId(currentBranchId.value, currentPage.value);
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('员工删除失败');
    }
  }
};

// 打开分配员工到支行弹窗
const assignToBranch = (employeeId) => {
  assignEmployee.value.employee_id = employeeId;
  assignDialogVisible.value = true;
};

const confirmAssign = () => {
  assignFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      const formData = {
                employee_id: assignEmployee.value.employee_id,
                branch_id: assignEmployee.value.branch_id
            };
      console.log('分配员工到支行请求参数:', formData);
      const response = await request.put('/employees/assign', formData);
      if (response.code === 0) {
        ElMessage.success('员工分配成功');
        assignDialogVisible.value = false;
        getEmployeesByBranchId(assignEmployee.value.branch_id, currentPage.value);
        
        // 重置表单数据和验证状态
        resetAssignForm();
      }
    } catch (error) {
      console.error('分配员工到支行失败:', error);
      ElMessage.error('员工分配失败');
    }
  });
};

// 重置分配表单
const resetAssignForm = () => {
  assignFormRef.value?.resetFields();
  assignEmployee.value = {
    employee_id: '',
    branch_id: ''
  };
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getEmployeesByBranchId(currentBranchId.value);
};

const handleCurrentPageChange = (val) => {
  currentPage.value = val;
  getEmployeesByBranchId(currentBranchId.value);
};

onMounted(() => {
  getBranches();
  getEmployeesByBranchId(null);
});
</script>

<style scoped>
.employee-manage {
  padding: 20px;
}

.employee-list,
.add-employee-form {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>